import { reactive, ref, watch, unref, toRaw, computed, nextTick, h, watchEffect, markRaw, defineAsyncComponent } from 'vue';
import { useModal, useModalInner } from '/@/components/Modal';
import { ONL_FORM_TABLE_NAME, FormSchemaFactory, ONL_AUTH_PRE } from './FormSchemaFactory';
import { duplicateCheck } from '/@/views/system/user/user.api';
import { useUserStore } from '/@/store/modules/user';
import { defHttp } from '/@/utils/http/axios';
import { replaceAll, importViewsFile } from '/@/utils';
import * as CustomExpression from '/@/utils/desform/customExpression';
import { add } from '/@/components/Form/src/componentMap';
import OnlineSelectCascade from '../auto/comp/OnlineSelectCascade.vue';
import LinkTableSelect from '../extend/linkTable/LinkTableSelect.vue';
import LinkTableCard from '../extend/linkTable/LinkTableCard.vue';
import { usePermissionStore } from '/@/store/modules/permission';
import { filterMultiDictText } from '/@/utils/dict/JDictSelectUtil';
import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';
import { pick } from 'lodash-es';
import { useRouter } from 'vue-router';
import { getAreaTextByCode } from '/@/components/Form/src/utils/Area';
import { createImgPreview } from '/@/components/Preview/index';
import LinkTableListPiece from '../extend/linkTable/LinkTableListPiece.vue';
import dayjs from 'dayjs';

const ceKeys = Object.keys(CustomExpression);
const ceJoin = ceKeys.join(',');
const $CE$ = ceKeys.map((key) => CustomExpression[key]);
const normalRegExp = /#{([^}]+)?}/g;
const customRegExp = /{{([^}]+)?}}/g;
const fillRuleRegExp = /\${([^}]+)?}/g;
const ACTION_TYPES = { ADD: 'add', EDIT: 'edit', DETAIL: 'detail', RELOAD: 'reload' };
function initDefValueConfig(field2, item, config) {
  if (hasEffectiveValue(item.defVal)) {
    config.push({ field: field2, type: item.type, value: item.defVal });
  }
}
function initSubTableDefValueConfig(item, config) {
  if (hasEffectiveValue(item.fieldDefaultValue)) {
    config.push({ field: item.key, type: item.type, value: item.fieldDefaultValue });
  }
}
async function loadFormFieldsDefVal(properties, callback) {
  if (Array.isArray(properties) && properties.length > 0) {
    const formValues = {};
    for (const prop of properties) {
      let { value, type, field: field2 } = prop;
      value = await handleDefaultValue(value, ACTION_TYPES.ADD, {});
      if ('number' === type && value) {
        value = Number.parseFloat(value);
      }
      formValues[field2] = value;
    }
    callback(formValues);
  }
}
async function loadOneFieldDefVal(field2, item, formValues) {
  const { defVal, type } = item;
  if (hasEffectiveValue(defVal)) {
    let value = await handleDefaultValue(defVal, ACTION_TYPES.ADD, {});
    if ('number' === type && value) {
      value = Number.parseFloat(value);
    }
    formValues[field2] = value;
  }
}
function hasEffectiveValue(val) {
  if (val || val === 0) {
    return true;
  }
  return false;
}
async function handleDefaultValue(defVal, action, getFormData) {
  if (defVal != null) {
    if (checkExpressionType(defVal)) {
      const value = await getDefaultValue(defVal, action, getFormData);
      if (value != null) {
        return value;
      }
    }
  }
  return defVal;
}
function checkExpressionType(defVal) {
  let normalCount = 0,
    customCount = 0,
    fillRuleCount = 0;
  defVal.replace(fillRuleRegExp, () => fillRuleCount++);
  if (fillRuleCount > 1) {
    logWarn(`表达式[${defVal}]不合法：只能同时填写一个填值规则表达式！`);
    return false;
  }
  defVal.replace(normalRegExp, () => normalCount++);
  defVal.replace(customRegExp, () => customCount++);
  const fillRuleOtherCount = normalCount + customCount;
  if (fillRuleCount > 0 && fillRuleOtherCount > 0) {
    logWarn(`表达式[${defVal}]不合法：填值规则表达式不能和其他表达式混用！`);
    return false;
  }
  return true;
}
function getRegExpMap(text2, exp) {
  const map = /* @__PURE__ */ new Map();
  text2.replace(exp, function (match, param) {
    map.set(match, param.trim());
    return match;
  });
  return map;
}
async function getDefaultValue(defVal, action, getFormData) {
  if (action === ACTION_TYPES.ADD || action === ACTION_TYPES.RELOAD) {
    if (fillRuleRegExp.test(defVal)) {
      const arr = [getFormData];
      return await executeRegExp(defVal, fillRuleRegExp, executeFillRuleExpression, arr);
    }
  }
  if (action === ACTION_TYPES.ADD) {
    defVal = await executeRegExp(defVal, normalRegExp, executeNormalExpression);
    defVal = await executeRegExp(defVal, customRegExp, executeCustomExpression);
    return defVal;
  }
  return null;
}
async function executeRegExp(defVal, regExp, execFun, otherParams = []) {
  const map = getRegExpMap(defVal, regExp);
  for (const origin2 of map.keys()) {
    const exp = map.get(origin2);
    const result = await execFun.apply(null, [exp, origin2, ...otherParams]);
    if (origin2 === defVal) {
      return result;
    }
    defVal = replaceAll(defVal, origin2, result);
  }
  return defVal;
}
async function executeNormalExpression(expression2, origin2) {
  switch (expression2) {
    case 'date':
      return dayjs().format('YYYY-MM-DD');
    case 'time':
      return dayjs().format('HH:mm:ss');
    case 'datetime':
      return dayjs().format('YYYY-MM-DD HH:mm:ss');
    default:
      const result = getUserInfoByExpression(expression2);
      if (result != null) {
        return result;
      }
      return origin2;
  }
}
function getUserInfoByExpression(expression2) {
  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo;
  if (userInfo) {
    switch (expression2) {
      case 'sysUserId':
        return userInfo.id;
      case 'sysUserCode':
      case 'sys_user_code':
        return userInfo.username;
      case 'sysUserName':
        return userInfo.realname;
      case 'sysOrgCode':
      case 'sys_org_code':
        return userInfo.orgCode;
    }
  }
  return null;
}
async function executeCustomExpression(expression, origin) {
  const fn = eval(`(function (${ceJoin}){ return ${expression} })`);
  try {
    return fn.apply(null, $CE$);
  } catch (e) {
    logError(e);
    return origin;
  }
}
async function executeFillRuleExpression(expression2, origin2, getFormData) {
  const url = `/api-upms/sys/fillRule/executeRuleByCode/${expression2}`;
  let formData = {};
  if (typeof getFormData === 'function') {
    formData = getFormData();
  }
  const { success, msg, data } = await defHttp.put({ url, params: formData }, { isTransformResponse: false });
  if (success) {
    return data;
  } else {
    logError(`填值规则（${expression2}）执行失败：${msg}`);
    return origin2;
  }
}
function logWarn(message) {
  console.warn('[loadFieldDefVal]:', message);
}
function logError(message) {
  console.error('[loadFieldDefVal]:', message);
}
function useEnhance(onlineTableContext, isList = true) {
  const EnhanceJS = reactive({});
  const getAction = (url, params) => {
    return defHttp.get({ url, params }, { isTransformResponse: false });
  };
  const postAction = (url, params) => {
    return defHttp.post({ url, params }, { isTransformResponse: false });
  };
  const putAction = (url, params) => {
    return defHttp.put({ url, params }, { isTransformResponse: false });
  };
  const deleteAction = (url, params) => {
    return defHttp.delete({ url, params }, { isTransformResponse: false });
  };
  if (isList === true) {
    onlineTableContext['_getAction'] = getAction;
    onlineTableContext['_postAction'] = postAction;
    onlineTableContext['_putAction'] = putAction;
    onlineTableContext['_deleteAction'] = deleteAction;
  } else {
    onlineTableContext.addObject2Context('_getAction', getAction);
    onlineTableContext.addObject2Context('_postAction', postAction);
    onlineTableContext.addObject2Context('_putAction', putAction);
    onlineTableContext.addObject2Context('_deleteAction', deleteAction);
  }
  function initCgEnhanceJs(str) {
    if (str) {
      const Obj = eval('(' + str + ')');
      return new Obj(getAction, postAction, deleteAction);
    } else {
      return {};
    }
  }
  function triggerJsFun(that, buttonCode) {
    if (EnhanceJS && EnhanceJS[buttonCode]) {
      EnhanceJS[buttonCode](that);
    }
  }
  function customBeforeSubmit(that, formData) {
    if (EnhanceJS && EnhanceJS['beforeSubmit']) {
      return EnhanceJS['beforeSubmit'](that, formData);
    } else {
      return Promise.resolve();
    }
  }
  function beforeDelete(that, record2) {
    if (EnhanceJS && EnhanceJS['beforeDelete']) {
      return EnhanceJS['beforeDelete'](that, record2);
    } else {
      return Promise.resolve();
    }
  }
  if (isList === true) {
    if (onlineTableContext) {
      onlineTableContext['beforeDelete'] = (record2) => {
        const onlEnhanceJS = onlineTableContext['EnhanceJS'];
        if (onlEnhanceJS && onlEnhanceJS['beforeDelete']) {
          return onlEnhanceJS['beforeDelete'](onlineTableContext, record2);
        } else {
          return Promise.resolve();
        }
      };
      onlineTableContext['beforeEdit'] = (record2) => {
        const onlEnhanceJS = onlineTableContext['EnhanceJS'];
        if (onlEnhanceJS && onlEnhanceJS['beforeEdit']) {
          return onlEnhanceJS['beforeEdit'](onlineTableContext, record2);
        } else {
          return Promise.resolve();
        }
      };
    }
  }
  return {
    EnhanceJS,
    initCgEnhanceJs,
    customBeforeSubmit,
    beforeDelete,
    triggerJsFun,
  };
}

function useAutoModal(isBpm, { emit } = {}, callback) {
  const onlineFormCompRef = ref(null);
  const disableSubmit = ref(false);
  const formTemplate = ref(1);
  const cgButtonList = ref([]);
  const formRendered = ref(false);
  const modalMinWidth = ref(0);
  const isTreeForm = ref(false);
  const pidFieldName = ref('');
  const submitLoading = ref(false);
  const isUpdate = ref(false);
  const single = ref(true);
  const extConfigJson2 = reactive({});
  const showSub = ref(true);
  const customTitle = ref('');
  const successThenClose = ref(true);
  const topTipVisible = ref(false);
  const { popModalFixedWidth, resetBodyStyle, popBodyStyle } = useFixedHeightModal();
  const FORM_DISABLE_UPDATE = ref(false);
  const modalObject = {
    handleOpenModal: (_data) => {},
  };
  const tableName = ref('');
  const formDataId = ref('');
  const enableComment = ref(false);
  let onlineExtConfig = {};
  const title = computed(() => {
    const temp = customTitle.value;
    if (temp) {
      return temp;
    }
    if (unref(disableSubmit) === true) {
      return '详情';
    }
    if (unref(isUpdate) === true) {
      return '编辑';
    }
    return '新增';
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    customTitle.value = '';
    topTipVisible.value = false;
    if (isBpm === true) {
      await modalObject.handleOpenModal(data);
    } else {
      await handleOpenOnlineModal(data);
    }
    resetBodyStyle();
    if (callback) {
      callback();
    }
  });
  const loadItemSuccess = ref(false);
  async function getFormStatus() {
    await getRefPromise(loadItemSuccess);
    return FORM_DISABLE_UPDATE.value;
  }
  async function handleOpenOnlineModal(data) {
    setModalProps({ confirmLoading: false });
    isUpdate.value = data.isUpdate;
    disableSubmit.value = data.disableSubmit || false;
    if ((data == null ? void 0 : data.hideSub) === true) {
      showSub.value = false;
    }
    if (data == null ? void 0 : data.title) {
      customTitle.value = data.title;
    }
    if (data == null ? void 0 : data.record) {
      formDataId.value = data.record.id;
    } else {
      formDataId.value = '';
    }
    await nextTick(async () => {
      await getRefPromise(formRendered);
      handleCommentConfig();
      await onlineFormCompRef.value.show(
        data == null ? void 0 : data.isUpdate,
        data == null ? void 0 : data.record,
        data == null ? void 0 : data.param
      );
    });
  }
  function renderSuccess(extConfig) {
    formRendered.value = true;
    modalMinWidth.value = extConfig.modalMinWidth;
    if (extConfig.modelFullscreen == 1) {
      setModalProps({ defaultFullscreen: true });
    } else {
      setModalProps({ defaultFullscreen: false });
    }
    onlineExtConfig = extConfig;
  }
  function handleCommentConfig() {
    const dataIdValue = formDataId.value;
    if (onlineExtConfig['commentStatus'] == 1 && dataIdValue) {
      enableComment.value = true;
      setModalProps({ defaultFullscreen: true });
    } else {
      enableComment.value = false;
    }
  }
  const singleWidth = 800;
  const one2ManyWidth = 1100;
  const modalWidth = computed(() => {
    const diff = 200 * (formTemplate.value - 1);
    let width = (!unref(single) ? one2ManyWidth : singleWidth) + diff;
    width = calcModalMixWidth(width);
    const minWidth = modalMinWidth.value;
    console.log({ minWidth });
    if (minWidth && width < minWidth) {
      width = minWidth;
    }
    console.log({ width });
    return width;
  });
  function calcModalMixWidth(width) {
    let minWidth = extConfigJson2.modalMinWidth;
    if (minWidth != null && minWidth !== '') {
      try {
        minWidth = Number.parseInt(minWidth);
        if (width < minWidth) {
          return minWidth;
        }
      } catch (e) {
        console.warn('error modalMinWidth value: ', minWidth);
      }
    }
    return width;
  }
  function handleCgButtonClick(optType, buttonCode) {
    onlineFormCompRef.value.handleCgButtonClick(optType, buttonCode);
  }
  function handleSubmit() {
    submitLoading.value = true;
    setTimeout(() => {
      submitLoading.value = false;
    }, 1500);
    onlineFormCompRef.value.handleSubmit();
  }
  function handleCancel() {
    closeModal();
  }
  function loadFormItems(id, params = {}) {
    const url = `/api-online/online/cgform/api/getFormItem/${id}`;
    return new Promise((resolve, reject) => {
      defHttp
        .get({ url, params }, { isTransformResponse: false })
        .then((res) => {
          console.log('表单结果》》modal:', res);
          if (res.success) {
            resolve(res.data);
          } else {
            reject(res.msg);
          }
        })
        .catch(() => {
          reject();
        });
    });
  }
  async function handleFormConfig(id, params) {
    const result = await loadFormItems(id, params);
    const dataFormTemplate = result.head.formTemplate;
    formTemplate.value = dataFormTemplate ? Number(dataFormTemplate) : 1;
    cgButtonList.value = result.cgButtonList;
    isTreeForm.value = result.head.isTree === 'Y';
    pidFieldName.value = result.head.treeParentIdField || '';
    tableName.value = result.head.tableName;
    if (result['form_disable_update'] === true) {
      FORM_DISABLE_UPDATE.value = true;
    } else {
      FORM_DISABLE_UPDATE.value = false;
    }
    loadItemSuccess.value = true;
    emit && emit('formConfig', result);
    await nextTick(async () => {
      const myForm = await getRefPromise(onlineFormCompRef);
      await myForm.createRootProperties(result);
    });
  }
  function handleSuccess(formData) {
    formData[ONL_FORM_TABLE_NAME] = tableName.value;
    emit('success', formData);
    if (successThenClose.value == true) {
      closeModal();
    }
    topTipVisible.value = false;
    successThenClose.value = true;
  }
  function onCloseEvent() {
    if (onlineFormCompRef.value) {
      onlineFormCompRef.value.onCloseModal();
    }
  }
  return {
    title,
    modalWidth,
    registerModal,
    closeModal,
    modalObject,
    onCloseEvent,
    cgButtonList,
    handleCgButtonClick,
    disableSubmit,
    handleSubmit,
    submitLoading,
    handleCancel,
    successThenClose,
    handleSuccess,
    topTipVisible,
    handleFormConfig,
    onlineFormCompRef,
    formTemplate,
    isTreeForm,
    pidFieldName,
    renderSuccess,
    formRendered,
    isUpdate,
    showSub,
    tableName,
    formDataId,
    enableComment,
    popBodyStyle,
    popModalFixedWidth,
    getFormStatus,
  };
}
function useFixedHeightModal() {
  const minWidth = 800;
  const popModalFixedWidth = ref(800);
  let tempWidth = window.innerWidth - 300;
  if (tempWidth < minWidth) {
    tempWidth = minWidth;
  }
  popModalFixedWidth.value = tempWidth;
  const popBodyStyle = ref({});
  function resetBodyStyle() {
    const height = window.innerHeight - 210;
    popBodyStyle.value = {
      height: height + 'px',
      overflowY: 'auto',
    };
  }
  return {
    popModalFixedWidth,
    popBodyStyle,
    resetBodyStyle,
  };
}

function queryTableData(tableName, params) {
  const url = '/api-online/online/cgform/api/getData/' + tableName;
  return defHttp.get({ url, params });
}
function queryTableColumns(tableName, params) {
  const url = '/api-online/online/cgform/api/getColumns/' + tableName;
  return defHttp.get({ url, params });
}
function useLinkTable(props) {
  const pageNo = ref('1');
  const baseParam = ref({});
  const searchParam = ref({});
  const mainContentField = ref('');
  const auths = reactive({
    add: true,
    update: true,
  });
  const textFieldArray = computed(() => {
    if (props.textField) {
      return props.textField.split(',');
    }
    return [];
  });
  const otherColumns = ref([]);
  const realShowColumns = computed(() => {
    const columns2 = otherColumns.value;
    if (props.multi == true) {
      return columns2.slice(0, 3);
    } else {
      return columns2.slice(0, 6);
    }
  });
  watchEffect(async () => {
    const table = props.tableName;
    if (table) {
      const valueField = props.valueField || '';
      const textField = props.textField || '';
      const arr = [];
      if (valueField) {
        arr.push(valueField);
      }
      if (textField) {
        const temp = textField.split(',');
        mainContentField.value = temp[0];
        for (const field2 of temp) {
          arr.push(field2);
        }
      }
      const imageField = props.imageField || '';
      if (imageField) {
        arr.push(imageField);
      }
      baseParam.value = {
        linkTableSelectFields: arr.join(','),
      };
      await resetTableColumns();
      await reloadTableLinkOptions();
    }
  });
  const otherFields = computed(() => {
    const textField = props.textField || '';
    const others = [];
    let labelField = '';
    if (textField) {
      const temp = textField.split(',');
      labelField = temp[0];
      for (let i = 0; i < temp.length; i++) {
        if (i > 0) {
          others.push(temp[i]);
        }
      }
    }
    return {
      others,
      labelField,
    };
  });
  const selectOptions = ref([]);
  const tableColumns = ref([]);
  const dictOptions = ref({});
  async function resetTableColumns() {
    const params = baseParam.value;
    const data = await queryTableColumns(props.tableName, params);
    tableColumns.value = data.columns;
    if (data.columns) {
      const imageField = props.imageField;
      const arr = data.columns.filter((c) => c.dataIndex != mainContentField.value && c.dataIndex != imageField);
      otherColumns.value = arr;
    }
    dictOptions.value = data.dictOptions;
    console.log('隐藏的按钮', data.hideColumns);
    if (data.hideColumns) {
      const hideCols = data.hideColumns;
      if (hideCols.indexOf('add') >= 0) {
        auths.add = false;
      } else {
        auths.add = true;
      }
      if (hideCols.indexOf('update') >= 0) {
        auths.update = false;
      } else {
        auths.update = true;
      }
    }
  }
  async function reloadTableLinkOptions() {
    const params = getLoadDataParams();
    const data = await queryTableData(props.tableName, params);
    const records = data.records;
    const dataList = [];
    const { others, labelField } = otherFields.value;
    const imageField = props.imageField;
    if (records && records.length > 0) {
      for (const rd of records) {
        const temp = Object.assign({}, rd);
        transData(temp);
        const result = Object.assign({}, pick(temp, others), { id: temp.id, label: temp[labelField], value: temp[props.valueField] });
        if (imageField) {
          result[imageField] = temp[imageField];
        }
        dataList.push(result);
      }
    }
    dataList.push({});
    selectOptions.value = dataList;
  }
  function transData(data) {
    const columns2 = tableColumns.value;
    const dictInfo = dictOptions.value;
    for (const c of columns2) {
      const { dataIndex, customRender } = c;
      if (data[dataIndex] || data[dataIndex] === 0) {
        if (customRender && customRender == dataIndex) {
          if (dictInfo[customRender]) {
            data[dataIndex] = filterMultiDictText(dictInfo[customRender], data[dataIndex]);
          }
        }
      }
    }
  }
  function getLoadDataParams() {
    const params = Object.assign({ pageSize: 10, pageNo: pageNo.value }, baseParam.value, searchParam.value);
    return params;
  }
  function addQueryParams(text2) {
    if (!text2) {
      searchParam.value = {};
    } else {
      const arr = textFieldArray.value;
      const params = [];
      const fields = [];
      for (let i = 0; i < arr.length; i++) {
        if (i <= 1) {
          fields.push(arr[i]);
          params.push({ field: arr[i], rule: 'like', val: text2 });
        }
      }
      params['superQueryMatchType'] = 'or';
      params['superQueryParams'] = encodeURI(JSON.stringify(params));
      searchParam.value = params;
    }
  }
  async function loadOne(value) {
    if (!value) {
      return [];
    }
    const valueFieldName = props.valueField;
    const params = Object.assign({}, baseParam.value, {
      pageSize: 10,
      pageNo: pageNo.value,
    });
    params['superQueryMatchType'] = 'and';
    const valueCondition = [{ field: valueFieldName, rule: 'in', val: value }];
    params['superQueryParams'] = encodeURI(JSON.stringify(valueCondition));
    const data = await queryTableData(props.tableName, params);
    const records = data.records;
    const dataList = [];
    if (records && records.length > 0) {
      for (const item of records) {
        const temp = Object.assign({}, item);
        transData(temp);
        dataList.push(temp);
      }
    }
    return dataList;
  }
  function compareData(arr, value) {
    if (!arr || arr.length == 0) {
      return false;
    }
    const valueArray = value.split(',');
    if (valueArray.length != arr.length) {
      return false;
    }
    let flag = true;
    for (const item of arr) {
      const temp = item[props.valueField];
      if (valueArray.indexOf(temp) < 0) {
        flag = false;
      }
    }
    return flag;
  }
  function formatData(formData) {
    Object.keys(formData).map((k) => {
      if (formData[k] instanceof Array) {
        formData[k] = formData[k].join(',');
      }
    });
  }
  function initFormData(formData, linkFieldArray, record2) {
    if (!record2) {
      record2 = {};
    }
    if (linkFieldArray && linkFieldArray.length > 0) {
      for (const str2 of linkFieldArray) {
        const arr = str2.split(',');
        const field2 = arr[0];
        const dictField = arr[1];
        if (!formData[field2]) {
          const value = record2[dictField] || '';
          formData[field2] = [value];
        } else {
          formData[field2].push(record2[dictField]);
        }
      }
    }
  }
  function getImageAsBackground(item) {
    let url;
    if (props.imageField) {
      url = item[props.imageField];
      url = getFileAccessHttpUrl(url);
    }
    if (url) {
      return {
        backgroundImage: "url('" + url + "')",
      };
    }
    return {};
  }
  
  const showImage = computed(() => {
    if (props.imageField) {
      return true;
    } else {
      return false;
    }
  });
  return {
    pageNo,
    otherColumns,
    realShowColumns,
    selectOptions,
    reloadTableLinkOptions,
    textFieldArray,
    addQueryParams,
    tableColumns,
    transData,
    mainContentField,
    loadOne,
    compareData,
    formatData,
    initFormData,
    getImageAsBackground,
    showImage,
    auths,
  };
}

function useTableColumns(onlineTableContext, extConfigJson) {
  const router = useRouter();
  const columns = ref([]);
  const dictOptionInfo = ref({});
  const selectedKeys = ref([]);
  const rowSelection = ref(null);
  const enableScrollBar = ref(true);
  const tableScroll = computed(() => {
    if (enableScrollBar.value == true) {
      return void 0;
    } else {
      return { x: false };
    }
  });
  const [registerOnlineHrefModal, { openModal: openOnlineHrefModal }] = useModal();
  const hrefMainTableId = ref('');
  const [registerPopModal, { openModal: openPopModal }] = useModal();
  const popTableId = ref('');
  function handleColumnResult(result) {
    dictOptionInfo.value = result.dictOptions;
    if (result.checkboxFlag == 'Y') {
      rowSelection.value = {
        selectedRowKeys: selectedKeys,
        onChange: onSelectChange,
      };
    } else {
      rowSelection.value = null;
    }
    enableScrollBar.value = result.scrollFlag == 1;
    const dataColumns = result.columns;
    dataColumns.forEach((column) => {
      Object.keys(column).map((key) => {
        if (column[key] == null) {
          delete column[key];
        }
      });
    });
    const fieldHrefSlots = result.fieldHrefSlots;
    const fieldHrefSlotKeysMap = {};
    fieldHrefSlots.forEach((item) => (fieldHrefSlotKeysMap[item.slotName] = item));
    let tableColumns = [];
    tableColumns = handleColumnHrefAndDict(dataColumns, fieldHrefSlotKeysMap);
    bpmStatusFilter(tableColumns);
    console.log('-----列表列配置----', tableColumns);
    if (onlineTableContext.isTree() === true) {
      const firstField = result.textField;
      let index = -1;
      for (let i = 0; i < tableColumns.length; i++) {
        if (tableColumns[i].dataIndex == firstField) {
          index = i;
          break;
        }
      }
      if (index > 0) {
        const deleteColumns = tableColumns.splice(index, 1);
        tableColumns.unshift(deleteColumns[0]);
      }
      if (tableColumns.length > 0) {
        tableColumns[0].align = 'left';
      }
    }
    columns.value = tableColumns;
    onlineTableContext.reloadTable();
  }
  function onSelectChange(selectedRowKeys, selectedRows) {
    selectedKeys.value = selectedRowKeys;
    onlineTableContext['selectedRows'] = toRaw(selectedRows);
    onlineTableContext['selectedRowKeys'] = toRaw(selectedRowKeys);
  }
  function handleColumnHrefAndDict(columns2, fieldHrefSlotKeysMap) {
    for (const column of columns2) {
      let { customRender, hrefSlotName, fieldType } = column;
      if (fieldType == 'date' || fieldType == 'Date') {
        column.customRender = ({ text: text2 }) => {
          if (!text2) {
            return '';
          }
          if (text2.length > 10) {
            return text2.substring(0, 10);
          }
          return text2;
        };
      } else if (fieldType == 'link_table') {
        column.customRender = ({ text: text2, record: record2 }) => {
          if (!text2) {
            return '';
          }
          if (onlineTableContext.isPopList === true) {
            return record2[column.dataIndex + '_dictText'];
          } else {
            const tempIdArray = (text2 + '').split(',');
            const tempLabelArray = record2[column.dataIndex + '_dictText'].split(',');
            const renderResult = [];
            for (let i = 0; i < tempIdArray.length; i++) {
              const renderObj = h(LinkTableListPiece, {
                id: tempIdArray[i],
                text: tempLabelArray[i],
                onTab: (id) => handleClickLinkTable(id, hrefSlotName),
              });
              renderResult.push(renderObj);
            }
            if (renderResult.length == 0) {
              return '';
            }
            return h('div', { style: { overflow: 'hidden' } }, renderResult);
          }
        };
      } else {
        if (!hrefSlotName && column.scopedSlots && column.scopedSlots.customRender) {
          if (fieldHrefSlotKeysMap.hasOwnProperty(column.scopedSlots.customRender)) {
            hrefSlotName = column.scopedSlots.customRender;
          }
        }
        if (customRender || hrefSlotName) {
          const dictCode = customRender;
          const replaceFlag = '_replace_text_';
          column.ellipsis = true;
          column.customRender = ({ text: text2, record: record2 }) => {
            let value = text2;
            if (dictCode) {
              if (dictCode.startsWith(replaceFlag)) {
                const textFieldName = dictCode.replace(replaceFlag, '');
                value = record2[textFieldName];
              } else {
                value = filterMultiDictText(unref(dictOptionInfo)[dictCode], text2 + '');
              }
            }
            if (column.showLength) {
              if (value && value.length > column.showLength) {
                value = value.substr(0, column.showLength) + '...';
              }
            }
            if (hrefSlotName) {
              const field2 = fieldHrefSlotKeysMap[hrefSlotName];
              if (field2) {
                return h(
                  'a',
                  {
                    onClick: () => handleClickFieldHref(field2, record2),
                  },
                  value
                );
              }
            }
            return value;
          };
        }
        if (column.scopedSlots) {
          column.ellipsis = true;
          const slots = column.scopedSlots;
          column['slots'] = slots;
          delete column.scopedSlots;
        }
      }
    }
    return columns2;
  }
  function handleClickFieldHref(field, record) {
    let href = field.href;
    const urlPattern = /(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?/;
    const compPattern = /\.vue(\?.*)?$/;
    const jsPattern = /{{([^}]+)}}/g;
    if (typeof href === 'string') {
      if (href.startsWith('ONLINE:')) {
        const arr = href.split(':');
        hrefMainTableId.value = arr[1];
        const fieldName = arr[2];
        openOnlineHrefModal(true, {
          isUpdate: true,
          disableSubmit: true,
          hideSub: true,
          record: { id: record[fieldName] },
        });
      } else {
        href = href.trim().replace(/\${([^}]+)?}/g, (_s1, s2) => record[s2]);
        if (jsPattern.test(href)) {
          href = href.replace(jsPattern, function (text, s0) {
            try {
              return eval(s0);
            } catch (e) {
              console.error(e);
              return text;
            }
          });
        }
        if (urlPattern.test(href)) {
          window.open(href, '_blank');
        } else if (compPattern.test(href)) {
          openHrefCompModal(href);
        } else {
          router.push(href);
        }
      }
    }
  }
  const dialogStyle = {
    top: 0,
    left: 0,
    height: '100%',
    margin: 0,
    padding: 0,
  };
  const hrefComponent = reactive({
    model: {
      title: '',
      okText: '关闭',
      width: '100%',
      visible: false,
      destroyOnClose: true,
      style: dialogStyle,
      bodyStyle: { padding: '8px', height: 'calc(100vh - 108px)', overflow: 'auto', overflowX: 'hidden' },
      cancelButtonProps: { style: { display: 'none' } },
    },
    on: {
      ok: () => (hrefComponent.model.visible = false),
      cancel: () => (hrefComponent.model.visible = false),
    },
    is: null,
    params: {},
  });
  function openHrefCompModal(href2) {
    const index = href2.indexOf('?');
    let path = href2;
    if (index !== -1) {
      path = href2.substring(0, index);
      const paramString = href2.substring(index + 1, href2.length);
      const paramArray = paramString.split('&');
      const params = {};
      paramArray.forEach((paramObject) => {
        const paramItem = paramObject.split('=');
        params[paramItem[0]] = paramItem[1];
      });
      hrefComponent.params = params;
    } else {
      hrefComponent.params = {};
    }
    hrefComponent.model.visible = true;
    hrefComponent.model.title = '操作';
    hrefComponent.is = markRaw(defineAsyncComponent(() => importViewsFile(path)));
  }
  let fixedAction = 'left';
  if (onlineTableContext.isTree()) {
    fixedAction = 'right';
  }
  const actionColumn = reactive({
    title: '操作',
    dataIndex: 'action',
    slots: { customRender: 'action' },
    fixed: fixedAction,
    align: 'center',
    width: 150,
  });
  watch(
    () => (extConfigJson == null ? void 0 : extConfigJson.value),
    () => {
      let _a, _b;
      if (((_a = extConfigJson == null ? void 0 : extConfigJson.value) == null ? void 0 : _a.tableFixedAction) === 1) {
        actionColumn.fixed = ((_b = extConfigJson == null ? void 0 : extConfigJson.value) == null ? void 0 : _b.tableFixedActionType) || 'right';
        if (onlineTableContext.isTree()) {
          actionColumn.fixed = 'right';
        }
      }
    }
  );
  function bpmStatusFilter(tableColumns) {
    let flag = false;
    for (let i = 0; i < tableColumns.length; i++) {
      const item = tableColumns[i];
      const fieldName = item.dataIndex;
      if (fieldName.toLowerCase() == 'bpm_status') {
        flag = true;
        break;
      }
    }
    onlineTableContext['hasBpmStatus'] = flag;
    return flag;
  }
  function downloadRowFile(text2) {
    if (!text2) {
      return;
    }
    if (text2.indexOf(',') > 0) {
      text2 = text2.substring(0, text2.indexOf(','));
    }
    const url = getFileAccessHttpUrl(text2);
    window.open(url);
  }
  function getImgView(text2) {
    if (text2 && text2.indexOf(',') > 0) {
      text2 = text2.substring(0, text2.indexOf(','));
    }
    return getFileAccessHttpUrl(text2);
  }
  function getPcaText(code) {
    if (!code) {
      return '';
    }
    return getAreaTextByCode(code);
  }
  function getFormatDate(text2) {
    if (!text2) {
      return '';
    }
    let a = text2;
    if (a.length > 10) {
      a = a.substring(0, 10);
    }
    return a;
  }
  watch(selectedKeys, () => {
    onlineTableContext['selectedRowKeys'] = toRaw(selectedKeys.value);
  });
  onlineTableContext['clearSelectedRow'] = () => {
    selectedKeys.value = [];
    onlineTableContext['selectedRows'] = [];
    onlineTableContext['selectedRowKeys'] = [];
  };
  function viewOnlineCellImage(text2) {
    if (text2) {
      const imgList = [];
      const arr = text2.split(',');
      for (const str2 of arr) {
        if (str2) {
          imgList.push(getFileAccessHttpUrl(str2));
        }
      }
      createImgPreview({ imageList: imgList });
    }
  }
  const onlinePopModalRef = ref();
  async function handleClickLinkTable(id, hrefTableName) {
    popTableId.value = hrefTableName;
    const formStatus = await onlinePopModalRef.value.getFormStatus();
    if (formStatus == true) {
      hrefMainTableId.value = hrefTableName;
      openOnlineHrefModal(true, {
        isUpdate: true,
        disableSubmit: true,
        hideSub: true,
        record: { id },
      });
    } else {
      openPopModal(true, {
        isUpdate: true,
        record: {
          id,
        },
      });
    }
  }
  return {
    columns,
    actionColumn,
    selectedKeys,
    rowSelection,
    enableScrollBar,
    tableScroll,
    downloadRowFile,
    getImgView,
    getPcaText,
    getFormatDate,
    handleColumnResult,
    onSelectChange,
    hrefComponent,
    viewOnlineCellImage,
    hrefMainTableId,
    registerOnlineHrefModal,
    registerPopModal,
    openPopModal,
    openOnlineHrefModal,
    onlinePopModalRef,
    popTableId,
  };
}

const LINK_DOWN = 'link_down';
const LINK_TABLE_FIELD = 'link_table_field';
const LINK_TABLE = 'link_table';
function useFormItems(props, onlineFormRef) {
  add('OnlineSelectCascade', OnlineSelectCascade);
  add('LinkTableSelect', LinkTableSelect);
  add('LinkTableCard', LinkTableCard);
  const modalClass = props.modalClass;
  const formSchemas = ref([]);
  const tableName = ref('');
  const dbData = ref({});
  const fieldDisplayStatus = reactive({});
  const hasSubTable = ref(false);
  const subTabInfo = ref([]);
  const subDataSource = ref({});
  const refMap = {};
  const linkDownList = ref([]);
  const defaultValueFields = reactive({});
  const baseColProps = ref('');
  baseColProps.value = { sm: 24, xs: 24, md: 12, lg: 12, xl: 12, xxl: 12 };
  function createFormSchemas(properties, required, checkOnlyFieldValue2) {
    clearObj(defaultValueFields);
    defaultValueFields[tableName.value] = [];
    const subInfo = [];
    const arr = [];
    const hideFields = [];
    const dataSourceObj = {};
    const tableLinkInfo = {};
    Object.keys(properties).map((key) => {
      const item = properties[key];
      if (item.view == 'tab') {
        hasSubTable.value = true;
        defaultValueFields[key] = [];
        const temp = {
          key,
          foreignKey: item['foreignKey'],
          describe: item.describe,
          relationType: item.relationType,
          requiredFields: item.required || [],
          order: item.order,
          id: item.id,
        };
        if (item.relationType == 1) {
          refMap[key] = ref(null);
          temp['properties'] = item.properties;
        } else {
          dealSubProerties(item);
          refMap[key] = ref();
          temp['columns'] = item.columns;
          dataSourceObj[key] = [];
        }
        subInfo.push(temp);
        handleSubTableButtonAuth(key, item);
      } else {
        initDefValueConfig(key, item, defaultValueFields[tableName.value]);
        if (item.view === LINK_DOWN) {
          const array = handleLinkDown(item, key);
          for (const linkDownItem of array) {
            fieldDisplayStatus[linkDownItem.key] = true;
            fieldDisplayStatus[linkDownItem.key + '_load'] = true;
            const temp = FormSchemaFactory.createFormSchema(linkDownItem.key, linkDownItem);
            if (checkOnlyFieldValue2) {
              temp.setOnlyValidateFun(checkOnlyFieldValue2);
            }
            temp.isRequired(required);
            temp.setFormRef(onlineFormRef);
            temp.handleWidgetAttr(item);
            const tempIndex = getFieldIndex(arr, linkDownItem.key);
            if (tempIndex == -1) {
              arr.push(temp);
            } else {
              arr[tempIndex] = temp;
            }
          }
        } else {
          fieldDisplayStatus[key] = true;
          fieldDisplayStatus[key + '_load'] = true;
          const tempIndex = getFieldIndex(arr, key);
          if (tempIndex == -1) {
            const temp = FormSchemaFactory.createFormSchema(key, item);
            if (checkOnlyFieldValue2) {
              temp.setOnlyValidateFun(checkOnlyFieldValue2);
            }
            temp.isRequired(required);
            temp.setFormRef(onlineFormRef);
            arr.push(temp);
            hideFields.push(...temp.getRelatedHideFields());
            if (item.view === LINK_TABLE_FIELD) {
              const tempInfo = temp.getLinkFieldInfo();
              if (tempInfo) {
                if (tableLinkInfo[tempInfo[0]]) {
                  const tableLinkInfoEle = tableLinkInfo[tempInfo[0]];
                  tableLinkInfoEle.push(tempInfo[1]);
                } else {
                  tableLinkInfo[tempInfo[0]] = [tempInfo[1]];
                }
              }
            }
          }
        }
      }
    });
    arr.sort(function (a, b) {
      return a.order - b.order;
    });
    const formSchemaArray = [];
    formSchemaArray.push(FormSchemaFactory.createIdField());
    for (const a of arr) {
      if (a['view'] && a['view'] == LINK_TABLE) {
        if (tableLinkInfo[a.field]) {
          a.setOtherInfo(tableLinkInfo[a.field]);
        }
      }
      if (hideFields.indexOf(a.field) >= 0) {
        a.isHidden();
      }
      if (modalClass) {
        a.setCustomPopContainer(modalClass);
      }
      formSchemaArray.push(a.getFormItemSchema());
    }
    formSchemas.value = formSchemaArray;
    subInfo.sort(function (a, b) {
      return a.order - b.order;
    });
    subTabInfo.value = subInfo;
    subDataSource.value = dataSourceObj;
  }
  watch(
    fieldDisplayStatus,
    (val) => {
      const ref2 = onlineFormRef.value;
      const arr = [];
      const map = toRaw(val);
      Object.keys(map).map((k) => {
        if (k.endsWith('_load')) {
        } else {
          const item = {
            field: k,
            show: map[k],
          };
          const loadKey = k + '_load';
          if (map.hasOwnProperty(loadKey)) {
            item['ifShow'] = map[loadKey];
          }
          arr.push(item);
        }
      });
      if (ref2) {
        ref2.updateSchema(arr);
      }
    },
    { immediate: false }
  );
  function dealSubProerties(subInfo) {
    useOnlineVxeTableColumns(subInfo, (column) => {
      initSubTableDefValueConfig(column, defaultValueFields[subInfo.key]);
    });
  }
  watch(
    () => props.formTemplate,
    () => {
      baseColProps.value = getFormItemColProps();
    },
    { immediate: true }
  );
  function getFormItemColProps() {
    const temp = props.formTemplate;
    if (temp == 2) {
      return { sm: 24, xs: 24, md: 12, lg: 12, xl: 12, xxl: 12 };
    } else if (temp == 3) {
      return { sm: 24, xs: 24, md: 8, lg: 8, xl: 8, xxl: 8 };
    } else if (temp == 4) {
      return { sm: 24, xs: 24, md: 6, lg: 6, xl: 6, xxl: 6 };
    } else {
      return {
        span: 24,
      };
    }
  }
  function checkOnlyFieldValue(rule, value) {
    return new Promise((resolve) => {
      if (!value) {
        resolve('');
      }
      const realTableName = tableName.value.replace(/\$\d+/, '');
      const param = {
        tableName: realTableName,
        fieldName: rule.field,
        fieldVal: value,
      };
      const formData = dbData.value;
      if (formData.id) {
        param['dataId'] = formData.id;
      }
      duplicateCheck(param)
        .then((res) => {
          if (res.success) {
            resolve('');
          } else {
            resolve(res.msg);
          }
        })
        .catch((msg) => {
          resolve(msg);
        });
    });
  }
  function changeDataIfArray2String(data) {
    Object.keys(data).map((k) => {
      if (data[k]) {
        if (data[k] instanceof Array) {
          data[k] = data[k].join(',');
        }
      }
    });
    return data;
  }
  return {
    formSchemas,
    defaultValueFields,
    tableName,
    dbData,
    checkOnlyFieldValue,
    createFormSchemas,
    fieldDisplayStatus,
    subTabInfo,
    hasSubTable,
    subDataSource,
    baseColProps,
    changeDataIfArray2String,
    linkDownList,
    refMap,
  };
}
function useOnlineVxeTableColumns(subInfo, callback) {
  const vxeTypeMap = {
    inputNumber: 'input-number',
    sel_depart: 'depart-select',
    sel_user: 'user-select',
    list_multi: 'select-multiple',
    input_pop: 'textarea',
    sel_search: 'select-search',
    'select-dict-search': 'selectDictSearch',
  };
  subInfo.columns.forEach((column) => {
    if (column.type === 'radio') {
      column.type = 'select';
    } else if (vxeTypeMap[column.type]) {
      column.type = vxeTypeMap[column.type];
    } else if (column.type === 'popup') {
      handleSubPopup(column);
    }
    if (column.type === 'depart-select') {
      column['checkStrictly'] = true;
    }
    if (column.type === 'user-select') {
      handleSubUserSelect(column);
    }
    if ((column.width == 120 || column.width == '120px') && (column.type == 'image' || column.type == 'file')) {
      column.width = '130px';
    }
    if (!column.width) {
      column.width = '200px';
    }
    if (callback) {
      callback(column);
    }
  });
  function handleSubPopup(column) {
    const { destFields, orgFields } = column;
    const fieldConfig = [];
    if (!destFields || destFields.length == 0);
    else {
      const arr1 = destFields.split(',');
      const arr2 = orgFields.split(',');
      for (let i = 0; i < arr1.length; i++) {
        fieldConfig.push({
          target: arr1[i],
          source: arr2[i],
        });
      }
    }
    column.fieldConfig = fieldConfig;
  }
  function handleSubUserSelect(column) {
    const str2 = column.fieldExtendJson;
    let isRadioSelection = false;
    if (str2) {
      try {
        const json = JSON.parse(str2);
        if (json.multiSelect === false) {
          isRadioSelection = true;
        }
      } catch (e) {
        console.log('子表获取用户组件的扩展配置出现错误', e);
      }
    }
    column.isRadioSelection = isRadioSelection;
  }
}
function useOnlineFormContext() {
  const that = {};
  const CONTEXT_DESCRIPTION = {};
  const onlineFormContext = new Proxy(CONTEXT_DESCRIPTION, {
    get(_target, prop) {
      return Reflect.get(that, prop);
    },
  });
  function addObject2Context(prop, object) {
    that[prop] = object;
  }
  function resetContext(context) {
    Object.keys(context).map((k) => {
      that[k] = context[k];
    });
  }
  addObject2Context('$nextTick', nextTick);
  addObject2Context('addObject2Context', addObject2Context);
  return { onlineFormContext, addObject2Context, resetContext };
}
function handleLinkDown(item, field2) {
  const {
    config: { table, key, txt, linkField, idField, pidField, condition },
    others,
    order,
    title,
  } = item;
  const commonProp = {
    dictTable: table,
    dictText: txt,
    dictCode: key,
    pidField,
    idField,
    view: LINK_DOWN,
    type: item.type,
  };
  const array = [];
  const main = Object.assign(
    {
      key: field2,
      title,
      order,
      condition,
      origin: true,
    },
    commonProp
  );
  if (linkField && linkField.length > 0) {
    const fields = linkField.split(',');
    main['next'] = fields[0];
    for (let i = 0; i < fields.length; i++) {
      for (const o of others) {
        if (o.field == fields[i]) {
          const temp = Object.assign(
            {
              key: o.field,
              title: o.title,
              order: o.order,
              origin: false,
            },
            commonProp
          );
          if (i + 1 < fields.length) {
            temp['next'] = fields[i + 1];
          }
          array.push(temp);
        }
      }
    }
  }
  array.push(main);
  return array;
}
function getFieldIndex(arr, key) {
  let index = -1;
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (item.field === key) {
      index = i;
      break;
    }
  }
  return index;
}
function getRefPromise(componentRef) {
  return new Promise((resolve) => {
    (function next() {
      const ref2 = componentRef.value;
      if (ref2) {
        resolve(ref2);
      } else {
        setTimeout(() => {
          next();
        }, 100);
      }
    })();
  });
}
function clearObj(obj) {
  Object.keys(obj).map((k) => {
    delete obj[k];
  });
}
const permissionStore = usePermissionStore();
function handleSubTableButtonAuth(tableName, item) {
  let arr = item.hideButtons;
  const code = ONL_AUTH_PRE + tableName + ':';
  if (!arr) {
    arr = [];
  }
  permissionStore.setOnlineSubTableAuth(code, arr);
}
function getDetailFormSchemas(props) {
  const detailFormSchemas = ref([]);
  const refMap = {};
  const hasSubTable = ref(false);
  const subTabInfo = ref([]);
  const subDataSource = ref({});
  const formSpan = computed(() => {
    const temp = props.formTemplate;
    if (temp == '2') {
      return 12;
    } else if (temp == '3') {
      return 8;
    } else if (temp == '4') {
      return 6;
    } else {
      return 24;
    }
  });
  function createFormSchemas(properties) {
    const subInfo = [];
    console.log('111', properties);
    const arr = [];
    const dataSourceObj = {};
    Object.keys(properties).map((key) => {
      const item = properties[key];
      if (item.view == 'tab') {
        hasSubTable.value = true;
        const temp = {
          key,
          foreignKey: item['foreignKey'],
          describe: item.describe,
          relationType: item.relationType,
          requiredFields: item.required || [],
          order: item.order,
        };
        if (item.relationType == 1) {
          refMap[key] = ref(null);
          temp['properties'] = item.properties;
        } else {
          dealSubProerties(item);
          refMap[key] = ref();
          temp['columns'] = item.columns;
          dataSourceObj[key] = [];
        }
        subInfo.push(temp);
      } else {
        if (item.view === LINK_DOWN) {
          const array = handleLinkDown2(item, key);
          for (const linkDownItem of array) {
            const tempIndex = getFieldIndex2(arr, linkDownItem.key);
            const temp = {
              field: linkDownItem.key,
              label: linkDownItem.title,
              view: linkDownItem.view,
              order: linkDownItem.order,
              dictTable: linkDownItem.dictTable,
              linkField: linkDownItem.linkField || '',
            };
            if (tempIndex == -1) {
              arr.push(temp);
            } else {
              arr[tempIndex] = temp;
            }
          }
        } else if (item.view == 'hidden');
        else {
          const tempIndex = getFieldIndex2(arr, key);
          if (tempIndex == -1) {
            const temp = Object.assign(
              {
                field: key,
                label: item.title,
              },
              pick(item, ['view', 'order', 'fieldExtendJson', 'dictTable', 'dictText', 'dictCode', 'dict'])
            );
            if (item.view == 'file') {
              temp['span'] = 24;
              temp['isFile'] = true;
            }
            if (item.view == 'image') {
              temp['span'] = 24;
              temp['isImage'] = true;
            }
            if (item.view == 'link_table') {
              if (item.fieldExtendJson) {
                try {
                  const json = JSON.parse(item.fieldExtendJson);
                  if (json.showType != 'select') {
                    temp['isCard'] = true;
                  }
                  if (json.multiSelect == true) {
                    temp['multi'] = true;
                  }
                } catch (e) {
                  console.error('解析json字符串出错', item.fieldExtendJson);
                }
              }
            }
            if (item.view == 'umeditor' || item.view == 'markdown') {
              temp['isHtml'] = true;
              temp['span'] = 24;
            }
            arr.push(temp);
          }
        }
      }
    });
    arr.sort(function (a, b) {
      return a.order - b.order;
    });
    subInfo.sort(function (a, b) {
      return a.order - b.order;
    });
    subTabInfo.value = subInfo;
    console.log('wang---subTabInfo-02', subTabInfo);
    for (let i = 0; i < arr.length; i++) {
      const temp = arr[i];
      if (temp.isFile === true || temp.isImage === true || temp.isHtml === true) {
        if (i > 0) {
          const last = arr[i - 1];
          const span = last.span || formSpan.value;
          last.span = span;
        }
      }
    }
    detailFormSchemas.value = arr;
    subDataSource.value = dataSourceObj;
    console.log('adadad', arr);
  }
  function dealSubProerties(subInfo) {
    useOnlineVxeTableColumns(subInfo);
  }
  function getFieldIndex2(arr, key) {
    let index = -1;
    for (let i = 0; i < arr.length; i++) {
      const item = arr[i];
      if (item.field === key) {
        index = i;
        break;
      }
    }
    return index;
  }
  function handleLinkDown2(item, field2) {
    const all = [];
    const {
      config: { table, key, txt, linkField },
      order,
      title,
      others,
    } = item;
    const obj = {
      table,
      key,
      txt,
    };
    const temp = {
      view: 'link_down',
      order,
      title,
      dictTable: JSON.stringify(obj),
    };
    all.push(Object.assign({}, { linkField, key: field2 }, temp));
    if (linkField) {
      const arr = linkField.split(',');
      for (const a of arr) {
        let title2 = '';
        for (const o of others) {
          if (o.field == a) {
            title2 = o.title;
          }
        }
        all.push(Object.assign({}, { key: a }, temp, { title: title2 }));
      }
    }
    return all;
  }
  return {
    detailFormSchemas,
    hasSubTable,
    subTabInfo,
    refMap,
    createFormSchemas,
    formSpan,
    subDataSource,
  };
}
export {
  useFormItems,
  useEnhance,
  getDetailFormSchemas,
  loadOneFieldDefVal,
  LINK_DOWN,
  getRefPromise,
  handleLinkDown,
  getFieldIndex,
  useTableColumns,
  useAutoModal,
  loadFormFieldsDefVal,
  useOnlineFormContext,
  useLinkTable,
  useFixedHeightModal,
};
